package cx.zan.web.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import cx.zan.utils.RRHolder;
import cx.zan.vo.ResultVo;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author Mxb
 * @version 1.0
 * @date 2020/3/30 15:06
 */

public class BaseServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //接受post请求 调用doGet()方法执行
        doGet(request,response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String md = request.getParameter("md");
        if (md == null || md.length() == 0) {
            ResultVo vo = new ResultVo(ResultVo.CODE_FAILED, null, "参数不合法");
            //转json
            //ObjectMapper mapper = new ObjectMapper();
            //String s = mapper.writeValueAsString(vo);
            //System.out.println(vo);
            //response.getWriter().print(s);
            //return;
            writeJson(vo);
        }

        try {
            Method method = this.getClass().getMethod(md, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this, request, response);

        } catch (Exception e) {
            e.printStackTrace();
            //response.getWriter().print("滚蛋");
            ResultVo vo = new ResultVo(ResultVo.CODE_FAILED, null, "发生异常");
            //转json
            //ObjectMapper mapper = new ObjectMapper();
            //String s = mapper.writeValueAsString(vo);
            //System.out.println(vo);
            //response.getWriter().print(s);
            writeJson(vo);
            return;
        }
    }
    //必须每次返回内容个，不管啥 json格式
    public void writeJson(ResultVo resultVo) throws IOException {
        //转json
        ObjectMapper mapper = new ObjectMapper();
        String s = mapper.writeValueAsString(resultVo);
        //System.out.println(resultVo);
        // 难点
        //response.getWriter().print(s);
        RRHolder.getResponse().getWriter().print(s);
    }

    /**
     * 返回 请求失败
     * @param data
     * @throws IOException
     */
    public void writeFail(Object data) throws IOException {
        ResultVo vo = new ResultVo(ResultVo.CODE_FAILED,data,"请求失败！");
        writeJson(vo);
    }

    /**
     * 返回请求成功
     * @param data
     * @throws IOException
     */
    public void writeSuccess(Object data) throws IOException {
        ResultVo vo = new ResultVo(ResultVo.CODE_SUCCESS,data,"请求成功！");
        writeJson(vo);
    }

}
